<template>
	<div>
		<div class="department">
			<!-- 按钮区域 -->
			<div class="addRoom_box">
				<el-button type="danger" class="mt10 mr30" style="border-radius: 10px" @click="handleBatchDelete"> 批量删除 </el-button>
				<el-button type="primary" class="mt10 mr30" style="border-radius: 10px" @click="handleAddDoctor"> 新增医生信息 </el-button>
			</div>

			<!-- 医生管理主体区域 -->
			<div class="department_box">
				<div class="room_title">医生管理</div>

				<!-- 搜索部分 -->
				<div class="search_box">
					<el-select
						clearable
						v-model="searchParams.depart_id"
						placeholder="科室选择"
						class="ml20 mr20"
						style="width: 200px"
						@change="handleDepartSearch"
					>
						<el-option v-for="dept in departmentList" :key="dept.id" :label="dept.name" :value="dept.id"></el-option>
					</el-select>
					<el-input placeholder="输入医生名称" v-model="searchParams.name" class="search_input" style="width: 200px" @input="handleInputSearch">
						<template #suffix>
							<el-icon v-if="searchParams.name" class="el-input__icon" @click="clearNameSearch">
								<Close />
							</el-icon>
							<el-icon v-else class="el-input__icon">
								<Search />
							</el-icon>
						</template>
					</el-input>
				</div>

				<!-- 医生表格 -->
				<el-table
					:data="tableData"
					style="width: 100%; margin-bottom: 20px"
					row-key="id"
					default-expand-all
					ref="tableRef"
					v-loading="loading"
					element-loading-text="正在加载数据..."
					:cell-class-name="cellClassName"
					@selection-change="handleSelectionChange"
				>
					<el-table-column type="selection" width="55" align="center" />
					<el-table-column prop="name" label="医生姓名" align="center" width="80" />
					<el-table-column label="头像" align="center" width="90">
						<template #default="scope">
							<el-image
								:src="getFullImageUrl(scope.row.avatar)"
								:preview-src-list="[getFullImageUrl(scope.row.avatar)]"
								style="width: 50px; height: 50px; border-radius: 50%"
								fit="cover"
								alt="医生头像"
								:error="
									() => {
										console.log('图片加载失败:', scope.row.avatar);
										return true;
									}
								"
								preview-teleported
							></el-image>
						</template>
					</el-table-column>
					<el-table-column prop="duties" label="职称" align="center" width="120" />
					<el-table-column label="科室" align="center" width="120">
						<template #default="scope">
							<span>
								{{ getDepartmentName(scope.row.depart_id) }}
							</span>
						</template>
					</el-table-column>
					<el-table-column label="标签" align="center">
						<template #default="scope">
							<div class="tags-container">
								<el-button
									v-for="tagId in Array.isArray(scope.row.tar_id) ? scope.row.tar_id : scope.row.tar_id ? scope.row.tar_id.split(',') : []"
									:key="tagId"
									:style="{
										backgroundColor: getTagStyle(tagId, 'back'),
										color: getTagStyle(tagId, 'color'),
										border: 'none',
										marginRight: '5px',
										marginBottom: '5px',
									}"
									size="small"
									plain
								>
									{{ getTagName(tagId) }}
								</el-button>
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="good" label="擅长" align="center">
						<template #default="scope">
							<div class="ellipsis-cell" :title="scope.row.good">
								{{ scope.row.good }}
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="create_time" label="创建时间" align="center" width="150" />
					<el-table-column label="操作" align="center" width="180">
						<template #default="scope">
							<div class="operation-buttons">
								<el-button type="primary" plain size="small" @click="handleEdit(scope.row)" class="operation-button">编辑</el-button>
								<el-button type="danger" plain size="small" @click="handleSingleDelete(scope.row)" class="operation-button">删除</el-button>
							</div>
						</template>
					</el-table-column>
				</el-table>

				<!-- 无数据提示 -->
				<div v-if="tableData.length === 0 && !loading" class="no-data">
					<el-empty description="暂无数据"></el-empty>
				</div>

				<!-- 分页 -->
				<el-pagination
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="searchParams.page"
					:page-sizes="[10, 20, 50, 100]"
					:page-size="searchParams.limit"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
					background
					class="pagination"
					:disabled="loading"
				>
				</el-pagination>
			</div>

			<!-- 新增/编辑医生弹窗 -->
			<el-dialog :title="dialogTitle" v-model="dialogVisible" width="800px" @close="handleDialogClose" :z-index="2000">
				<el-form :model="doctorForm" :rules="doctorRules" ref="doctorFormRef" label-width="100px">
					<el-form-item label="医生姓名" prop="name">
						<el-input v-model="doctorForm.name" placeholder="请输入医生姓名"></el-input>
					</el-form-item>

					<el-form-item label="挂号费" prop="money">
						<el-input v-model.number="doctorForm.money" placeholder="请输入挂号费" type="number" min="0"></el-input>
					</el-form-item>

					<el-form-item label="性别" prop="sex">
						<el-select v-model="doctorForm.sex" placeholder="请选择性别" style="width: 100%">
							<el-option label="男" value="1"></el-option>
							<el-option label="女" value="2"></el-option>
						</el-select>
					</el-form-item>

					<el-form-item label="所属医院" prop="hospital_id">
						<el-select v-model="doctorForm.hospital_id" placeholder="请选择所属医院" clearable style="width: 100%">
							<el-option v-for="hospital in hospitalList" :key="hospital.id" :label="hospital.name" :value="hospital.id"></el-option>
						</el-select>
					</el-form-item>

					<el-form-item label="所属科室" prop="depart_id">
						<el-select v-model="doctorForm.depart_id" placeholder="请选择所属科室" clearable style="width: 100%">
							<el-option v-for="dept in departmentList" :key="dept.id" :label="dept.name" :value="dept.id"></el-option>
						</el-select>
					</el-form-item>

					<el-form-item label="医生职称" prop="duties">
						<el-input v-model="doctorForm.duties" placeholder="请输入医生职称"></el-input>
					</el-form-item>

					<el-form-item label="医生头像" prop="avatar">
						<div class="avatar-upload-container">
							<el-upload
								class="avatar-uploader"
								action="/pc/Fileimg/file"
								:show-file-list="false"
								:on-success="handleAvatarSuccess"
								:before-upload="beforeAvatarUpload"
								:disabled="loading || uploadLoading"
								:on-progress="handleUploadProgress"
								:on-error="handleUploadError"
								ref="uploadRef"
								:headers="uploadHeaders"
								style='border: 1px #C0C4CC dashed;border-radius: 5px;'
							>
								<template #default>
									<div v-if="doctorForm.avatar && !uploadLoading" class="avatar-wrapper">
										<img :src="getFullImageUrl(doctorForm.avatar)" class="avatar" alt="医生头像" />
										<div class="avatar-overlay">
											<el-icon class="edit-icon"><Edit /></el-icon>
											<span class="edit-text">更换头像</span>
										</div>
									</div>
									<el-icon v-else-if="!uploadLoading" class="avatar-uploader-icon"><Plus /></el-icon>
									<div v-else class="uploading">
										<el-progress :percentage="uploadPercentage" stroke-width="4" style="width: 120px"></el-progress>
										<span class="uploading-text">上传中...</span>
									</div>
								</template>
							</el-upload>

							<!-- 上传提示 -->
							<div class="upload-hint">支持JPG、PNG格式，文件大小不超过2MB</div>

							<!-- 上传错误提示 -->
							<el-alert
								v-if="uploadError"
								:message="uploadError"
								type="error"
								show-icon
								:closable="true"
								@close="uploadError = ''"
								style="margin-top: 10px; padding: 5px 15px"
							></el-alert>
						</div>
					</el-form-item>

					<el-form-item label="医生标签" prop="tar_id">
						<el-select v-model="doctorForm.tar_id" placeholder="请选择医生标签" multiple style="width: 100%">
							<el-option v-for="tag in tagList" :key="tag.id" :label="tag.name" :value="tag.name"></el-option>
						</el-select>
					</el-form-item>

					<el-form-item label="状态" prop="status">
						<el-switch v-model="doctorForm.status" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用"></el-switch>
					</el-form-item>

					<el-form-item label="医生简介" prop="content" class="editor-container">
						<vue-ueditor-wrap v-model="doctorForm.content" :config="editorConfig" editor-id="editor-demo-02"></vue-ueditor-wrap>
					</el-form-item>
				</el-form>
				<template #footer>
					<span class="dialog-footer">
						<el-button @click="handleDialogClose" :disabled="loading || uploadLoading">取 消</el-button>
						<el-button type="primary" @click="submitDoctorForm" :disabled="loading || uploadLoading">保 存</el-button>
					</span>
				</template>
			</el-dialog>

			<!-- 删除确认弹窗
			<el-dialog title="确认删除" v-model="deleteDialogVisible" width="30%" :before-close="handleDeleteCancel" :z-index="2000">
				<p>确定要删除选中的医生数据吗？此操作不可撤销。</p>
				<template #footer>
					<span class="dialog-footer">
						<el-button @click="handleDeleteCancel" :disabled="loading">取 消</el-button>
						<el-button type="danger" @click="confirmDelete" :disabled="loading">确 定</el-button>
					</span>
				</template>
			</el-dialog> -->
		</div>
	</div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, nextTick } from 'vue';
import { Plus, Search, Close, Edit } from '@element-plus/icons-vue';
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';

import { getDoctorList, deleteDoctor, addDoctor, getDepartmentList, getHospitalList, getTagList, upload } from '/@/api/doctor/index.ts';
import { Session } from '/@/utils/storage'; // 新增引入

// 基础配置
const url = 'https://yiliao.kuxia.top/';
const { proxy } = getCurrentInstance();

// 表格数据
const tableData = ref([]);
const total = ref(0);
const loading = ref(false); // 加载状态
const tableRef = ref(null);

// 搜索条件
const searchParams = reactive({
	name: '',
	depart_id: '',
	page: 1,
	limit: 10,
});

// 搜索定时器 - 防抖处理
let searchTimer = null;

// 下拉框数据
const departmentList = ref([]);
const hospitalList = ref([]);
const tagList = ref([]);

// 弹窗控制
const dialogVisible = ref(false);
const dialogTitle = ref('新增医生信息');
// 删除弹窗已移除，因为使用了 $confirm 方法
// const deleteDialogVisible = ref(false);

// 选中的删除ID
const selectedDeleteIds = ref([]);

// 医生表单数据
const doctorForm = reactive({
	id: '',
	name: '',
	money: '', // 挂号费
	depart_id: '',
	duties: '',
	avatar: '',
	tar_id: [],
	status: 1,
	content: '', // 介绍
	good: '',
	sex: '1', // 性别默认为1(男)
});

// 表单验证规则
const doctorRules = ref({
	name: [{ required: true, message: '请输入医生姓名', trigger: 'blur' }],
	money: [
		{ required: true, message: '请输入挂号费', trigger: 'blur' },
		{ type: 'number', message: '挂号费必须为数字', trigger: 'blur' },
	],
	depart_id: [{ required: true, message: '请选择所属科室', trigger: 'change' }],
	duties: [{ required: true, message: '请输入医生职称', trigger: 'blur' }],
	content: [{ required: true, message: '请输入医生介绍', trigger: 'blur' }],
	sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
	avatar: [{ required: true, message: '请上传医生头像', trigger: 'change' }],
	tar_id: [{ required: true, message: '请选择医生标签', trigger: 'change' }],
});

// 上传相关状态
const uploadLoading = ref(false); // 上传中状态
const uploadPercentage = ref(0); // 上传进度百分比
const uploadError = ref(''); // 上传错误信息
const uploadUrl = ref('/api/upload'); // 上传URL

// 表单引用
const doctorFormRef = ref(null);
const quillEditorRef = ref(null);
const uploadRef = ref(null);

// 初始化数据
onMounted(() => {
	fetchDoctorList();
	fetchDepartmentList();
	fetchHospitalList();
	fetchTagList();
});

// 获取医生列表
const fetchDoctorList = async () => {
  try {
    loading.value = true;

    // 构建请求参数
    const params = {};

    // 添加搜索条件
    if (searchParams.name && searchParams.name.trim()) {
      params.name = searchParams.name.trim();
    }

    if (searchParams.depart_id !== null && searchParams.depart_id !== undefined && searchParams.depart_id !== '') {
      params.depart_id = searchParams.depart_id;
    }

    console.log('请求参数:', params);

    // 发起请求
    const res = await getDoctorList().signIn(params);
    console.log('医生列表响应:', res);

    // 处理响应数据
    if (res && res.code === 1) {
      // 标准化数据结构
      let allData = [];

      if (Array.isArray(res.data)) {
        allData = res.data;
      } else if (res.data && typeof res.data === 'object') {
        if (Array.isArray(res.data.list)) {
          allData = res.data.list;
        } else if (Array.isArray(res.data.data)) {
          allData = res.data.data;
        }
      }

      // 检查数据是否包含ID字段
      console.log('检查数据ID字段:', allData.map(item => ({id: item.id, name: item.name})));

      // 根据搜索条件过滤数据
      let filteredData = allData;

      // 根据科室ID过滤
      if (searchParams.depart_id !== null && searchParams.depart_id !== undefined && searchParams.depart_id !== '') {
        filteredData = filteredData.filter(
          (item) =>
            item.depart_id == searchParams.depart_id ||
            (item.depart_name && item.depart_name.includes(departmentList.value.find((d) => d.id == searchParams.depart_id)?.name))
        );
      }

      // 根据医生姓名过滤
      if (searchParams.name && searchParams.name.trim()) {
        const searchName = searchParams.name.trim().toLowerCase();
        filteredData = filteredData.filter((item) => item.name && item.name.toLowerCase().includes(searchName));
      }

      // 前端分页处理
      total.value = filteredData.length;
      const start = (searchParams.page - 1) * searchParams.limit;
      const end = start + searchParams.limit;
      tableData.value = filteredData.slice(start, end);
      
      // 添加调试信息
      console.log('当前页面数据:', tableData.value.map(item => ({id: item.id, name: item.name})));
    } else {
      tableData.value = [];
      total.value = 0;
      const errorMsg = res && res.msg ? res.msg : '获取医生列表失败';
      proxy.$message.error(errorMsg);
    }
  } catch (error) {
    tableData.value = [];
    total.value = 0;
    console.error('获取医生列表异常:', error);

    if (error && error.message) {
      if (error.message.includes('Network Error')) {
        proxy.$message.error('网络错误，请检查网络连接');
      } else if (error.message.includes('timeout')) {
        proxy.$message.error('请求超时，请稍后重试');
      } else {
        proxy.$message.error('获取医生列表异常: ' + error.message);
      }
    } else {
      proxy.$message.error('获取医生列表时发生未知错误');
    }
  } finally {
    loading.value = false;
  }
};

// 获取科室列表
const fetchDepartmentList = async () => {
	try {
		const res = await getDepartmentList().signIn({});
		if (res.code === 1) {
			departmentList.value = res.data || [];
		} else {
			proxy.$message.error(res.msg || '获取科室列表失败');
		}
	} catch (error) {
		proxy.$message.error('获取科室列表异常');
		console.error(error);
	}
};

// 获取医院列表
const fetchHospitalList = async () => {
	try {
		const res = await getHospitalList().signIn({});
		if (res.code === 1) {
			hospitalList.value = res.data || [];
		} else {
			proxy.$message.error(res.msg || '获取医院列表失败');
		}
	} catch (error) {
		proxy.$message.error('获取医院列表异常');
		console.error(error);
	}
};

// 获取标签列表
const fetchTagList = async () => {
	try {
		const res = await getTagList().signIn({});
		if (res.code === 1) {
			tagList.value = res.data || [];
		} else {
			proxy.$message.error(res.msg || '获取标签列表失败');
		}
	} catch (error) {
		proxy.$message.error('获取标签列表异常');
		console.error(error);
	}
};

// 科室搜索处理
const handleDepartSearch = (value) => {
	if (searchTimer) {
		clearTimeout(searchTimer);
	}

	searchParams.depart_id = value !== undefined && value !== null ? value : '';
	searchParams.page = 1;

	searchTimer = setTimeout(() => {
		fetchDoctorList();
	}, 300);
};

// 输入搜索处理（防抖）
const handleInputSearch = (value) => {
	if (searchTimer) {
		clearTimeout(searchTimer);
	}

	searchParams.name = value !== undefined ? value : '';
	searchParams.page = 1;

	searchTimer = setTimeout(() => {
		fetchDoctorList();
	}, 500);
};

// 清除姓名搜索
const clearNameSearch = () => {
	searchParams.name = '';
	searchParams.depart_id = '';
	searchParams.page = 1;
	nextTick(() => {
		fetchDoctorList();
	});
};

// 分页大小改变
const handleSizeChange = (newSize) => {
	const size = Number(newSize) || 10;
	searchParams.limit = size;
	searchParams.page = 1;
	fetchDoctorList();
};

// 当前页改变
const handleCurrentChange = (newPage) => {
	const page = Number(newPage) || 1;
	searchParams.page = page;
	fetchDoctorList();
};

// 批量删除
const handleBatchDelete = () => {
  if (!tableRef.value) return;

  // 使用 getSelectionRows 方法获取选中行
  const selection = tableRef.value.getSelectionRows();
  
  // 添加调试信息
  console.log('选中的行数据:', selection);
  
  if (!selection || selection.length === 0) {
    proxy.$message.warning('请选择要删除的数据');
    return;
  }

  // 检查选中行是否包含ID
  const validSelection = selection.filter(item => item.id);
  if (validSelection.length === 0) {
    proxy.$message.error('选中的数据缺少ID信息，无法删除');
    return;
  }

  if (validSelection.length !== selection.length) {
    proxy.$message.warning('部分选中数据缺少ID信息，仅删除有效数据');
  }

  // 显示确认信息，包括将要删除的医生姓名
  const doctorNames = validSelection.map(item => item.name).join('、');
  selectedDeleteIds.value = validSelection.map((item) => item.id);
  
  proxy.$msgbox({
    title: '删除确认',
    message: `确定要删除以下${validSelection.length}位医生吗？
              <div style="margin: 10px 0; font-weight: bold">${doctorNames}</div>
              <span style="color: #f56565; font-size: 12px;">此操作不可撤销</span>`,
    type: 'warning',
    dangerouslyUseHTMLString: true,
    showCancelButton: true,
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    center: true
  }).then(() => {
    confirmDelete();
  }).catch(() => {
    proxy.$message.info('已取消删除');
    selectedDeleteIds.value = [];
  });
};

// 单个删除
const handleSingleDelete = (row) => {
  // 检查行数据是否包含ID
  console.log('删除的行数据:', row);
  
  if (!row.id) {
    proxy.$message.error('该医生数据缺少ID信息，无法删除');
    return;
  }

  proxy.$msgbox({
    title: '删除确认',
    message: `确定要删除医生<strong>${row.name}</strong>吗？
              <div style="color: #f56565; font-size: 12px; margin-top: 10px;">此操作不可撤销</div>`,
    type: 'warning',
    dangerouslyUseHTMLString: true,
    showCancelButton: true,
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    center: true
  }).then(() => {
    selectedDeleteIds.value = [row.id];
    confirmDelete();
  }).catch(() => {
    proxy.$message.info('已取消删除');
    selectedDeleteIds.value = [];
  });
};

// 跟踪表格选中项变化
const handleSelectionChange = (selection) => {
  // 添加调试信息，查看选中项
  console.log('当前选中的项:', selection);
};

// 确认删除
const confirmDelete = async () => {
  // 检查是否有要删除的ID
  if (!selectedDeleteIds.value || selectedDeleteIds.value.length === 0) {
    proxy.$message.warning('没有选中要删除的数据');
    return;
  }

  // 过滤掉无效的ID
  const validIds = selectedDeleteIds.value.filter(id => id && id !== '');
  if (validIds.length === 0) {
    proxy.$message.error('选中的数据ID无效，无法删除');
    selectedDeleteIds.value = [];
    return;
  }

  if (validIds.length !== selectedDeleteIds.value.length) {
    proxy.$message.warning('部分选中数据ID无效，仅删除有效数据');
  }

  try {
    loading.value = true;
    
    // 显示正在删除的提示
    const loadingMessage = proxy.$message({
      message: '正在删除数据...',
      duration: 0,
      icon: 'Loading'
    });
    
    const res = await deleteDoctor().signIn({
      id: validIds.join(','),
    });

    // 关闭加载提示
    loadingMessage.close();

    if (res.code === 1) {
      proxy.$message.success(`${validIds.length > 1 ? '批量' : ''}删除成功`);
      // 如果当前页只有一条数据且删除的就是这条数据，则跳转到上一页
      if (tableData.value.length === validIds.length && searchParams.page > 1) {
        searchParams.page--;
      }
      fetchDoctorList();
    } else {
      proxy.$message.error(res.msg || '删除失败');
    }
  } catch (error) {
    proxy.$message.error('删除操作异常');
    console.error('删除操作异常:', error);
  } finally {
    loading.value = false;
    selectedDeleteIds.value = [];
  }
};

// 取消删除
// const handleDeleteCancel = () => {
// 	deleteDialogVisible.value = false;
// 	selectedDeleteIds.value = [];
// };

// 新增医生
const handleAddDoctor = async () => {
	dialogTitle.value = '新增医生信息';
	await resetForm();
	dialogVisible.value = true;
};

// 编辑医生
const handleEdit = (row) => {
	dialogTitle.value = '编辑医生信息';
	// 复制数据到表单
	Object.assign(doctorForm, { ...row });
	// 处理标签数据格式，将ID转换为名称
	if (row.tar_id && typeof row.tar_id === 'string') {
		const tagIds = row.tar_id.split(',');
		doctorForm.tar_id = tagIds.map((id) => {
			const tag = tagList.value.find((t) => t.id == id);
			return tag ? tag.name : id;
		});
	} else if (Array.isArray(row.tar_id)) {
		doctorForm.tar_id = row.tar_id.map((id) => {
			// 如果已经是名称则直接返回，否则查找对应名称
			if (typeof id === 'string' && !/^\d+$/.test(id)) {
				return id;
			}
			const tag = tagList.value.find((t) => t.id == id);
			return tag ? tag.name : id;
		});
	} else {
		doctorForm.tar_id = [];
	}
	// 确保ID是数字类型
	doctorForm.depart_id = row.depart_id ? Number(row.depart_id) : '';
	doctorForm.hospital_id = row.hospital_id ? Number(row.hospital_id) : '';
	// 处理性别数据显示
	doctorForm.sex = row.sex ? String(row.sex) : '1';
	dialogVisible.value = true;
};

// 富文本
const editorConfig = reactive({
    // 编辑器不自动被内容撑高
    autoHeightEnabled: false,
    // 初始容器高度
    initialFrameHeight: 200,
    // 初始容器宽度
    initialFrameWidth: '100vw',
    UEDITOR_HOME_URL: '/UEditor/', // 访问 UEditor 静态资源的根路径，可参考常见问题1
    serverUrl: '/pc/common/ueditor', // 服务端接⼝
    uploadUrl: '/UEditor',
});

// 关闭弹窗
const handleDialogClose = () => {
	dialogVisible.value = false;
	resetForm();
};

// 重置表单
const resetForm = async () => {
	// 重置表单验证状态
	if (doctorFormRef.value) {
		doctorFormRef.value.resetFields();
	}

	// 重置表单数据
	Object.keys(doctorForm).forEach((key) => {
		if (key === 'status') {
			doctorForm[key] = 1;
		} else if (key === 'tar_id') {
			doctorForm[key] = [];
		} else if (key === 'sex') {
			doctorForm[key] = '1';
		} else {
			doctorForm[key] = '';
		}
	});

	// 重置上传状态
	uploadLoading.value = false;
	uploadPercentage.value = 0;
	uploadError.value = '';

	// 确保富文本编辑器清空
	await nextTick();
	if (quillEditorRef.value) {
		quillEditorRef.value.setHTML('');
	}
};

// 提交表单
const submitDoctorForm = async () => {
	try {
		// 表单验证
		await doctorFormRef.value.validate();

		// 构造请求参数
		const requestData = {
			depart_id: doctorForm.depart_id,
			name: doctorForm.name,
			good: doctorForm.content.replace(/<[^>]+>/g, '').substring(0, 100),
			money: String(doctorForm.money),
			duties: doctorForm.duties,
			content: doctorForm.content,
			sex: String(doctorForm.sex),
			avatar: doctorForm.avatar,
			tar_id: doctorForm.tar_id
				.map((name) => {
					const tag = tagList.value.find((t) => t.name === name);
					return tag ? tag.id : name;
				})
				.join(','),
			status: String(doctorForm.status),
		};

		// 如果是编辑，添加id参数
		if (doctorForm.id) {
			requestData.id = String(doctorForm.id);
		}

		loading.value = true;
		const res = await addDoctor().signIn(requestData);

		if (res.code === 1) {
			proxy.$message.success(doctorForm.id ? '更新成功' : '新增成功');
			dialogVisible.value = false;
			fetchDoctorList();
		} else {
			proxy.$message.error(res.msg || (doctorForm.id ? '更新失败' : '新增失败'));
		}
	} catch (error) {
		if (error.name !== 'Error') {
			proxy.$message.error('提交操作异常');
			console.error(error);
		}
	} finally {
		loading.value = false;
	}
};

// 新增上传相关配置
const uploadHeaders = ref({
	token: Session.get('token') || '',
	id: '', // 根据实际情况设置用户ID
});

// 初始化数据
onMounted(() => {
	fetchDoctorList();
	fetchDepartmentList();
	fetchHospitalList();
	fetchTagList();
	setUploadHeaders(); // 初始化上传请求头
});

// 新增：设置上传请求头
const setUploadHeaders = () => {
	const token = Session.get('token');
	if (token) {
		uploadHeaders.value.token = token;
		// 这里应该从用户信息中获取实际的用户ID
		uploadHeaders.value.id = '43'; // 默认值，实际应该从用户信息中获取
	}
};

// 头像上传成功处理（保持原有逻辑）
const handleAvatarSuccess = (response) => {
	uploadLoading.value = false;
	uploadPercentage.value = 0;

	if (!response) {
		uploadError.value = '上传响应为空';
		return;
	}

	if (response.code === 1) {
		if (response.data && response.data.url) {
			doctorForm.avatar = response.data.url;
			uploadError.value = '';
			proxy.$message.success('头像上传成功');
		} else {
			uploadError.value = '服务器返回数据格式不正确';
		}
	} else {
		uploadError.value = response.msg || '上传失败，请重试';
	}
};

// 头像上传进度处理
const handleUploadProgress = (event) => {
	uploadLoading.value = true;
	if (event.total > 0) {
		// 确保进度条不会过早达到100%
		const percentage = Math.round((event.loaded / event.total) * 100);
		uploadPercentage.value = percentage < 100 ? percentage : 99;
	}
};

// 头像上传错误处理
const handleUploadError = (error) => {
	uploadLoading.value = false;
	uploadPercentage.value = 0;

	if (error && error.message) {
		if (error.message.includes('Network Error')) {
			uploadError.value = '网络错误，请检查网络连接';
		} else if (error.message.includes('timeout')) {
			uploadError.value = '上传超时，请重试';
		} else if (error.message.includes('401')) {
			uploadError.value = '身份验证失败，请重新登录';
		} else if (error.message.includes('403')) {
			uploadError.value = '没有权限上传图片';
		} else if (error.message.includes('413')) {
			uploadError.value = '文件过大，请选择小于2MB的图片';
		} else if (error.message.includes('500')) {
			uploadError.value = '服务器错误，请稍后重试';
		} else {
			uploadError.value = '上传失败: ' + error.message;
		}
	} else {
		uploadError.value = '上传失败，请重试';
	}
};

// 头像上传前验证
const beforeAvatarUpload = (file) => {
	// 清除之前的错误信息
	uploadError.value = '';

	// 检查文件类型
	const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
	if (!isJPGOrPNG) {
		uploadError.value = '上传头像图片只能是 JPG/PNG 格式!';
		return false;
	}

	// 检查文件大小
	const isLt2M = file.size / 1024 / 1024 < 2;
	if (!isLt2M) {
		uploadError.value = '上传头像图片大小不能超过 2MB!';
		return false;
	}

	// 显示上传进度
	uploadLoading.value = true;
	uploadPercentage.value = 0;

	// 允许默认上传流程
	return true;
};

// 取消上传
const cancelUpload = () => {
	if (uploadRef.value) {
		uploadRef.value.abort();
		uploadLoading.value = false;
		uploadPercentage.value = 0;
		uploadError.value = '上传已取消';
	}
};

// 根据科室ID获取科室名称
const getDepartmentName = (id) => {
	if (!id) return '';
	const dept = departmentList.value.find((item) => item.id === id);
	return dept ? dept.name : '';
};

// 根据标签ID获取标签名称
const getTagName = (id) => {
	if (!id) return '';
	const tag = tagList.value.find((item) => item.id == id);
	return tag ? tag.name : '';
};

// 根据标签ID获取标签样式
const getTagStyle = (id, type) => {
	if (!id || !type) return '';
	const tag = tagList.value.find((item) => item.id == id);
	return tag ? tag[type] : '';
};

// 获取完整图片URL
const getFullImageUrl = (imageUrl) => {
	if (!imageUrl) return '';
	if (imageUrl.startsWith('http')) {
		return imageUrl;
	}
	return url + imageUrl;
};

// 表格单元格样式处理
const cellClassName = () => {
	return 'cell-with-zindex';
};

</script>

<style scoped>
/* 富文本编辑器样式优化 */
.editor-container :deep(.el-form-item__content) {
	display: block !important;
	flex-direction: initial !important;
	flex-wrap: initial !important;
	justify-content: initial !important;
	align-items: initial !important;
	align-content: initial !important;
}
.addRoom_box {
	display: flex;
	width: 100%;
	height: 60px;
	background-color: #f3f8ff;
	align-items: center;
	justify-content: end;
	padding: 0 30px;
}

/* 科室部分 */
.department_box {
	width: 98%;
	min-height: 80vh;
	margin-left: 1%;
	border-radius: 5px;
	background: #fff;
	> .room_title {
		width: 100%;
		height: 50px;
		font-weight: 600;
		font-size: 21px;
		line-height: 50px;
		background-color: #fff;
		display: flex;
		justify-content: flex-start;
		padding-left: 20px;
	}
}

.search_box {
	display: flex;
	align-items: center;
	padding: 10px 0;
	flex-wrap: wrap;
}

.dialog-footer {
	text-align: right;
}

/* 富文本编辑器样式优化 */
.editor-container :deep(.el-form-item__content) {
  align-items: center;
  /* display: flex; */
  flex: 1;
  flex-wrap: wrap;
  font-size: var(--font-size);
  line-height: 32px;
  min-width: 0;
  position: relative;
  display: block !important;
  flex-direction: initial !important;
  flex-wrap: initial !important;
  justify-content: initial !important;
  align-content: initial !important;
}

.editor-container :deep(.el-form-item__content > *) {
  flex: none !important;
  flex-grow: 0 !important;
  flex-shrink: 0 !important;
  flex-basis: auto !important;
  width: 100% !important;
}

.editor-container :deep(.ql-container) {
  min-height: 200px;
  width: 100% !important;
}

.editor-container :deep(.ql-editor) {
  min-height: 160px;
  width: 100% !important;
}

.editor-container :deep(.ql-toolbar) {
  width: 100% !important;
}

/* 头像上传样式优化 */
.avatar-upload-container {
	display: flex;
	flex-direction: column;
	align-items: flex-start;
}

.avatar-uploader {
	position: relative;
}

.avatar-wrapper {
	position: relative;
	width: 178px;
	height: 178px;
	border-radius: 6px;
	overflow: hidden;
}

.avatar {
	width: 100%;
	height: 100%;
	object-fit: cover;
	transition: all 0.3s ease;
}

.avatar-overlay {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	color: white;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	opacity: 0;
	transition: opacity 0.3s ease;
	cursor: pointer;
}

.avatar-wrapper:hover .avatar-overlay {
	opacity: 1;
}

.avatar-wrapper:hover .avatar {
	transform: scale(1.05);
}

.edit-icon {
	font-size: 24px;
	margin-bottom: 8px;
}

.edit-text {
	font-size: 14px;
}

.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
	text-align: center;
}

.uploading {
	width: 178px;
	height: 178px;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}

.uploading-text {
	margin-top: 10px;
	font-size: 14px;
	color: #606266;
}

.upload-hint {
	margin-top: 8px;
	font-size: 12px;
	color: #909399;
}

/* 标签容器 */
.tags-container {
	display: flex;
	flex-wrap: wrap;
	gap: 4px;
	justify-content: center;
}

/* 无数据样式 */
.no-data {
	text-align: center;
	padding: 50px 0;
}

/* 间距类 */
.mt10 {
	margin-top: 10px;
}

.mr30 {
	margin-right: 30px;
}

.ml20 {
	margin-left: 20px;
}

.mr20 {
	margin-right: 20px;
}

.ml10 {
	margin-left: 10px;
}

/* 表格样式调整 */
.el-table {
	font-size: 12px;
	position: relative;
}

:deep(.el-table th) {
	font-size: 12px;
}

:deep(.el-table td) {
	font-size: 12px;
}

:deep(.el-table .el-button) {
	font-size: 12px;
	padding: 5px 10px;
}

/* 文字溢出省略号显示 */
.ellipsis-cell {
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	max-width: 200px;
	position: relative;
}

.ellipsis-cell:hover::after {
	content: attr(title);
	position: absolute;
	left: 0;
	top: 100%;
	background: #fff;
	padding: 5px;
	border: 1px solid #ebeef5;
	box-shadow: 0 2px 12px 0 rgba(240, 21, 21, 0.1);
	z-index: 3000;
	white-space: normal;
	word-break: break-all;
	max-width: 300px;
}

/* 表格操作列样式优化 */
.operation-buttons {
	position: relative;
	z-index: 1;
}

.operation-button {
	margin: 0 2px;
	transition: all 0.3s;
	z-index: 2;
	position: relative;
}

.operation-button:hover {
	transform: translateY(-1px);
	box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
	z-index: 10;
}

.ellipsis-cell:hover::after {
	content: attr(title);
	position: absolute;
	left: 0;
	top: 100%;
	background: #fff;
	padding: 5px;
	border: 1px solid #ebeef5;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	z-index: 1000;
	white-space: normal;
	word-break: break-all;
	max-width: 300px;
}

/* 解决层级冲突 */
:deep(.el-image-viewer__wrapper) {
	z-index: 3000 !important;
}

:deep(.el-dialog__wrapper) {
	z-index: 2000 !important;
}

:deep(.el-table .el-button) {
	z-index: 2;
	position: relative;
}

:deep(.el-table .el-button:hover) {
	z-index: 10;
}

/* 加载状态覆盖层层级 */
:deep(.el-loading-mask) {
	z-index: 100 !important;
}

/* 表格单元格样式调整 */
:deep(.cell-with-zindex) {
	position: relative;
}

/* 表格行悬停效果优化 */
:deep(.el-table__body tr:hover) {
	z-index: auto;
}

/* 确保表格内的所有内容都有合适的层级 */
:deep(.el-table .cell) {
	position: relative;
	z-index: 1;
}

/* 分页样式优化 */
.pagination {
	padding: 20px 0;
	display: flex;
	justify-content: center;
}

.editor-container :deep(.el-form-item__content > *) {
	flex: none !important;
	flex-grow: 0 !important;
	flex-shrink: 0 !important;
	flex-basis: auto !important;
	width: 100% !important;
}

.editor-container :deep(.ql-container) {
	min-height: 200px;
	width: 100% !important;
}

.editor-container :deep(.ql-editor) {
	min-height: 160px;
	width: 100% !important;
}

.editor-container :deep(.ql-toolbar) {
	width: 100% !important;
}
</style>
